import { getToken } from "@/utils/auth";
import { computed, ref } from "vue";

// 添加类型定义
interface Message {
  time: string;
  data: string;
  parsed: ParsedSSEData | null;
}

interface ParsedSSEData {
  id: string;
  created: number;
  model: string;
  reasoning_content: string;
  content: string;
}

export function useChatForm() {
  const sseUrl = ref<string>(import.meta.env.VITE_API_URL + "/ai/gen-form-chat");
  const messages = ref<Message[]>([]);
  const isConnected = ref<boolean>(false);
  const isInThinkTag = ref<boolean>(false);
  let eventSource: EventSource | null = null;
  const reasoningRef = ref<HTMLElement | null>(null);
  const answerRef = ref<HTMLElement | null>(null);

  // 计算推理过程（思考链）
  const reasoningChain = computed(() => {
    return messages.value
      .filter(m => m.parsed?.reasoning_content)
      .map(m => m.parsed?.reasoning_content)
      .join("");
  });

  // 计算最终答案
  const finalAnswer = computed(() => {
    const rawContent = messages.value
      .filter(m => m.parsed?.content)
      .map(m => m.parsed?.content)
      .join("");
    return rawContent;
  });

  // 滚动到底部的函数
  const scrollToBottom = (element: HTMLElement | null): void => {
    if (element) {
      // 获取实际的滚动容器（mockup-window 内的 overflow-y-auto 元素）
      const scrollContainer = element.querySelector(".overflow-y-auto");
      if (scrollContainer) {
        scrollContainer.scrollTop = scrollContainer.scrollHeight;
      }
    }
  };

  const parseSSEData = (data: string): ParsedSSEData | null => {
    try {
      const parsed = JSON.parse(data);

      // 判断是否结束
      if (parsed.choices?.[0]?.finish_reason == "stop") {
        disconnect();
      }

      // 检查是否直接返回了 reasoning_content 非异步就是这样
      const directReasoning = parsed.choices?.[0]?.delta?.reasoning_content;
      if (directReasoning) {
        return {
          id: parsed.id,
          created: parsed.created,
          model: parsed.model,
          reasoning_content: directReasoning,
          content: parsed.choices?.[0]?.delta?.content || ""
        };
      }

      // 一个字一个字输出
      const content = parsed.choices?.[0]?.delta?.content || "";

      // 处理 think 标签包裹的情况 tink是推理的过程
      if (content.includes("<think>")) {
        isInThinkTag.value = true;
        const startIndex = content.indexOf("<think>") + "<think>".length;
        return {
          id: parsed.id,
          created: parsed.created,
          model: parsed.model,
          reasoning_content: content.substring(startIndex),
          content: content.substring(0, content.indexOf("<think>"))
        };
      }

      if (content.includes("</think>")) {
        isInThinkTag.value = false;
        const endIndex = content.indexOf("</think>");
        return {
          id: parsed.id,
          created: parsed.created,
          model: parsed.model,
          reasoning_content: content.substring(0, endIndex),
          content: content.substring(endIndex + "</think>".length)
        };
      }

      // 根据状态决定内容归属
      return {
        id: parsed.id,
        created: parsed.created,
        model: parsed.model,
        reasoning_content: isInThinkTag.value ? content : "",
        content: isInThinkTag.value ? "" : content
      };
    } catch (e) {
      console.error("解析JSON失败:", e);
      return null;
    }
  };

  // 发送用户消息
  const openSendUserMsg = (msg: string, model: string) => {
    if (eventSource) {
      eventSource.close();
    }

    // 清空消息
    clearMessages();

    try {
      eventSource = new EventSource(sseUrl.value + "?msg=" + msg + "&model=" + model + "&Authorization=" + getToken());
      isConnected.value = true;

      eventSource.onmessage = event => {
        const parsed = parseSSEData(event.data);
        messages.value.push({
          time: new Date().toLocaleTimeString(),
          data: event.data,
          parsed: parsed
        });
      };

      eventSource.onerror = error => {
        console.error("SSE Error:", error);
        disconnect();
      };
    } catch (error) {
      console.error("Connection Error:", error);
      disconnect();
    }
  };

  const disconnect = () => {
    if (eventSource) {
      eventSource.close();
      eventSource = null;
    }
    isConnected.value = false;
  };

  const clearMessages = () => {
    messages.value = [];
  };

  return {
    sseUrl,
    messages,
    isConnected,
    openSendUserMsg,
    disconnect,
    clearMessages,
    reasoningChain,
    finalAnswer,
    reasoningRef,
    answerRef
  };
}
